package gbackup.command;


import gbackup.core.RemoteFile;
import gbackup.core.Shell;

import java.util.StringTokenizer;


public class LocalChangeDirectoryCommand extends Command {
	private static final String PARENT = "..";
	private static final String CURRENT = ".";

	public LocalChangeDirectoryCommand(Shell shell, String rawCommand) {
		super(shell, rawCommand);
	}

	@Override
	public void execute() {
		if (this._arguments.size() != 1) {
			this._outputPrintStream.println("Invalid Argument : [" + this._rawCommand + "]");
			return;
		}

		String path = this._arguments.get(0);
		java.io.File workingDirectory = null;
		if (path.startsWith(RemoteFile.pathSeperator))
			workingDirectory = this._shell.getLocalRootDirectory();
		else
			workingDirectory = this._shell.getLocalWorkingDirectory();

		StringTokenizer st = new StringTokenizer(path, RemoteFile.pathSeperator);
		while (st.hasMoreTokens()) {
			String p = st.nextToken();

			if (p.equals(LocalChangeDirectoryCommand.PARENT)) {
				if(workingDirectory != this._shell.getLocalRootDirectory()) workingDirectory = workingDirectory.getParentFile();
				continue;
			} else if (p.equals(LocalChangeDirectoryCommand.CURRENT)) {
				continue;
			}
			
			boolean found = false;
			this._outputPrintStream.println(workingDirectory.getAbsolutePath() + "===");
			for(java.io.File f : workingDirectory.listFiles()) {
				if(!f.isDirectory()) continue;
				if(!f.getName().equals(p)) continue;
				
				workingDirectory = f;
				found = true;
				break;
			}
			if(!found) {
				this._outputPrintStream.println("Local Directory Not Found : [" + this._rawCommand + "]");
				return;
			}
			
			this._shell.setLocalWorkingDirectory(workingDirectory);
		}
	}

}
